package com.sy.controller;

import com.sy.bean.client.Client;
import com.sy.bean.client.ClientContact;
import com.sy.bean.client.ClientQuery;
import com.sy.common.bean.PageBean;
import com.sy.common.bean.ResultBean;
import com.sy.common.controller.BaseController;
import com.sy.common.exception.ValidateException;
import com.sy.common.utils.BeanOfMap;
import com.sy.service.ClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(tags = "客户列表")
@RequestMapping("/api")
public class ClientController extends BaseController {
    @Autowired
    ClientService clientService;

    @ApiOperation("查询客户")
    @PostMapping("/client/query")
    public ResultBean<PageBean> query(@RequestBody ClientQuery client){
        PageBean bean=clientService.query(BeanOfMap.bom(client));
        return success("客户列表",bean);
    }

    @ApiOperation("批量删除")
    @DeleteMapping("/client/delete")
    public ResultBean batchDelete(@RequestParam("ids") List ids){
        int rs= clientService.batchDelete(ids);
        return rs>0?success("删除成功"):fail("删除失败");
    }

    @ApiOperation("保存客户")
    @PostMapping("/client/add")
    public ResultBean save(@RequestBody Client client){
        int rs=clientService.save(client);
        return gotoResult(rs,"保存");
    }

    @ApiOperation("查询联系人")
    @PostMapping("/client/contact")
    public ResultBean<PageBean> query(@RequestBody ClientContact clientContact){
        PageBean bean=clientService.query(BeanOfMap.bom(clientContact));
        return success("联系人列表",bean);
    }

    @ApiOperation("修改客户")
    @PutMapping("/client/update")
    public ResultBean update(@Validated @RequestBody Client client, BindingResult result){
        validate(result);
        if (null==client.getClientContactList()||client.getClientContactList().size()==0)
            throw new ValidateException("clientContactList","联系人不能为空");
        client.getClientContactList().forEach(clientContact -> {
            if (null==clientContact.getName()||"".equals(clientContact.getName()))
                throw new ValidateException("name","联系人名字不能为空");
        });
        int rs=clientService.update(client);
        return gotoResult(rs,"修改");
    }

    @ApiOperation("客户详情")
    @GetMapping("/client")
    public ResultBean get(int id){
        Client client=clientService.get(id);
        return success("客户详情",client);
    }
}
